import { useEffect } from 'react';
import {
    View, Text, ImageBackground, Image, TextInput, StyleSheet, Pressable, ScrollView, DeviceEventEmitter
} from 'react-native';
import { Link, router } from 'expo-router'
import AntDesign from '@expo/vector-icons/AntDesign';

import ProductServer from '../../../common/service/ProductServer';
import * as FORM from "../../../components/Form"
import { CFlex, CColor } from '../../../constant/css'
import ScrollList from '../../../components/ScrollList';
import util from '../../../common/utils/util';
import SearchBar, { SearchType, Input } from '../../../components/SearchBar';
import { RootView } from '../../../components/Layout';
import { useSetState, useCurrent } from '../../../common/hooks/index'
import Constant from '../../../constant/Constant';
import ProductItem from '../../../components/ProductItem';

export default function Tab() {
    const [state, setState] = useSetState({
        data: [],

        bar: [],

        searchIP: '',
        searchCategory: '',
        searchSource: '',
        searchStatus: '',

    })
    const [ref, setRef] = useCurrent({
        params: {
            page: 1,
            pageSize: 10,
            name: '',
            pIp: '',
            category: '',
            source: '',
            status: '',
        },
        refreshProduct: null,
    })

    const setParams = (obj = {}) => {
        const { params } = ref
        let temp = { ...params, ...obj }
        setRef({ params: temp })
    }

    useEffect(() => {
        loadProductList()
        loadProductCategory()

        const refreshProduct = DeviceEventEmitter.addListener('refreshProduct', () => {
            setParams({ page: 1 })
            loadProductList()
        })
        setRef({ refreshProduct })
        return () => {
            ref.refreshProduct?.remove?.()
        }
    }, [])

    const loadProductList = async () => {
        const { data } = state
        const { params } = ref
        const [err, res] = await ProductServer.loadProductList({ ...params })
        if (err) return util.showInfo(err)
        let result = res.data?.result || []
        if (params.page > 1) {
            if (result.length < params.pageSize) {
                setParams({ page: -1 })
            }
            result = data.concat(result)
        }
        setState({
            data: result
        })
    }

    const loadProductCategory = async () => {
        const [err, res] = await ProductServer.loadProductCategory()
        if (err) return util.showInfo(err)
        const { category, source, ip: pIp, status } = res.data || {};
        const result = [
            {
                key: 'pIp',
                title: 'IP',
                type: SearchType.SINGLE,
                data: pIp,
                value: ''
            },
            {
                key: 'category',
                title: '分类',
                type: SearchType.SINGLE,
                data: category,
                value: '',
            },
            {
                key: 'source',
                title: '货源',
                type: SearchType.SINGLE,
                data: source,
                value: '',
            },
            {
                key: 'status',
                title: '状态',
                type: SearchType.SINGLE,
                data: status,
                value: '',
            },
        ]
        setState({
            bar: result
        })
    }

    const renderNav = () =>
        <View style={[CFlex.row, CFlex.sc, { width: '100%' }]}>
            <View style={{ flex: 1 }}>
                <Input
                    showClear
                    title='搜索商品'
                    style={{ marginHorizontal: 10 }}
                    onSearch={(val) => {
                        setParams({
                            page: 1,
                            name: val,
                        })
                        loadProductList()
                    }}
                />
            </View>
            <View style={[CFlex.cc, { paddingRight: 10 }]}>
                <Pressable style={styles.nav} onPress={() => router.push('/product/addOrEdit')}>
                    <AntDesign name="pluscircleo" size={35} color={CColor.Black} />
                </Pressable>
            </View>
        </View>

    const renderSearchBar = () =>
        <SearchBar
            bg={CColor.White}
            data={state.bar}
            onclick={(_data) => {
                const result = _data.reduce((_, item) => (_[item.key] = item?.value?.value || '') && _, {})
                setParams({ page: 1, ...result })
                loadProductList()
            }}
        />

    const renderItem = ({ item, index }) =>
        <ProductItem
            key={item.pId}
            singleLast={index === state.data.length - 1 && state.data.length % 2 === 1}
            item={item}
            onclick={() => {
                util.ExpoRouter.router.push('/product/productDetail')
                util.ExpoRouter.router.setParams({ id: item.pId })
            }}
        />

    const renderList = () =>
        <ScrollList
            bg='#F5F5F5'
            data={state.data}
            renderItem={renderItem}
            numColumns={2}
            onRefresh={() => {
                const { page, pageSize } = ref.params
                setParams({ page: 1 })
                loadProductList()
            }}
            onLoadMore={() => {
                const { page, pageSize } = ref.params
                if (page === -1) return util.showInfo('O.0 老板跑路了,没有了~')
                setParams({ page: page + 1 })
                loadProductList()
            }}
        />

    return (
        <RootView bg={CColor.White}>
            {renderNav()}
            {renderSearchBar()}
            {renderList()}
        </RootView>
    );
}

const styles = StyleSheet.create({
    nav: {
        ...CFlex.cc,
        width: 40,
        height: 40,
    },
    navText: {
        color: CColor.Black,
        fontSize: 12,
        marginTop: 5,
    }
})
